<?php

namespace App\Models;

use App\Libs\DataFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{

    use DataFormat;

    protected $table = 'user';
    protected $dates = [''];

    //protected $guarded = ['id', 'created_at'];
    protected $fillable = ['username', 'phone', 'pwd', 'avatars', 'type', 'org_id', 'token', 'open_id'];

    public static $sexConf = [0=>'未知', 1=>'男', 2=>'女', ];

    public static $typeConf = [1=>'志愿者', 2=>'团队', 3=>'机构', 4=>'智多星', ];


    public static  $formatKey = ['id'=>'int', 'username'=>'string', 'avatars'=>'image_url', 'phone'=>'string', 'email'=>'string' ];


    public function volunteer()
    {
        return $this->hasOne('App\Models\Volunteer', 'user_id', 'id');
    }

    public function team()
    {
        return $this->hasOne('App\Models\Team', 'user_id', 'id');
    }

    public function org()
    {
        return $this->hasOne('App\Models\Org', 'id', 'org_id');
    }

    public function goodAt()
    {
        return $this->hasMany('App\Models\VolunteerGoodAt', 'user_id', 'id');
    }


    public function getAllInfo()
    {
        //Todo:关联志愿者的用户信息
        $data = User::format($this);

        $volunteer = Volunteer::format($this->volunteer);

        $data = array_merge($data, $volunteer);

        $goodAt = $this->goodAt;
        if(empty($goodAt))
        {
            $data['good_at'] = [];
        }else
        {
            foreach($goodAt as $value)
            {
                $data['good_at'][] = VolunteerGoodAt::format($value);
            }
        }

        $data['regitser_time'] = $this->created_at->toDateTimeString();
        $data['server_time'] = date('Y-m-d H:i:s');
        $data['have_pwd'] = empty($this->pwd)? 0:1;

        return $data;
    }
    public static function createToken()
    {
        return md5(microtime()).uniqid();
    }

    public function getUserAvatar()
    {
        switch ($this->type)
        {
            case 1:
                $tmp['username'] = !empty($this->volunteer->real_name)? $this->volunteer->real_name:$this->username;
                $tmp['avatars'] = $this->avatars;
                break;

            case 2:
                $tmp['username'] = $this->team->name;
                $tmp['avatars'] = $this->team->logo;
                break;

            case 3:
                $tmp['username'] = $this->org->name;
                $tmp['avatars'] = $this->org->logo;
                break;

            case 4:
                $tmp['username'] = '志多星';
                $tmp['avatars'] = $this->avatars;
                break;
        }
        $tmp['avatars'] = image_url($tmp['avatars']);
        $tmp['id'] = $this->id;

        return $tmp;
    }

}
